/*
 * @Author: EyeSklear 1814580085@qq.com
 * @Date: 2024-03-04 22:07:48
 * @LastEditors: EyeSklear 1814580085@qq.com
 * @LastEditTime: 2024-03-29 21:27:07
 * @FilePath: \Scene_Back\src\path-item-relational\path-item-relational.service.ts
 * @Description:
 *
 * Copyright (c) 2024 by EyeSklear , All Rights Reserved.
 */
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreatePathItemRelationalDto } from './dto/create-path-item-relational.dto';
import { UpdatePathItemRelationalDto } from './dto/update-path-item-relational.dto';
import { Repository, In } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { PathItemRelational } from './entities/path-item-relational.entity';

@Injectable()
export class PathItemRelationalService {

  constructor(
    @InjectRepository(PathItemRelational)
    private readonly pathItemRelationalRepository: Repository<PathItemRelational>,
  ) {}

  async create(createPathItemRelationalDto: CreatePathItemRelationalDto) {
    const pathItemRelational = this.pathItemRelationalRepository.create(
      createPathItemRelationalDto,
    );
    this.pathItemRelationalRepository.insert(pathItemRelational);
    return;
  }

  async findAll() {
    return this.pathItemRelationalRepository.find();
  }

  async getByPathIds(path_ids: string[]): Promise<PathItemRelational[]> {
    return this.pathItemRelationalRepository.find({
      where: { path_id: In(path_ids) },
      select: ['item_id', 'type'],
    });
  }

  async getByPathId(path_id: string): Promise<PathItemRelational[]> {
    return this.pathItemRelationalRepository.find({
      where: { path_id: path_id },
      select: ['item_id', 'type'],
    });
  }

  async findOne(id: string) {
    return this.pathItemRelationalRepository.findOne({ where: { id: id } });
  }

  async update(
    id: string,
    updatePathItemRelationalDto: UpdatePathItemRelationalDto,
  ): Promise<PathItemRelational | string> {
    const oldItem = await this.pathItemRelationalRepository.findOne({
      where: { id },
    });

    if (!oldItem) {
      throw new NotFoundException('该修改对象不存在');
    }

    const updatePathItemRelational = this.pathItemRelationalRepository.merge(
      oldItem,
      updatePathItemRelationalDto,
    );

    await this.pathItemRelationalRepository.save(updatePathItemRelational);

    // 返回更新后的实体或其他有用的信息
    return updatePathItemRelational;
  }

  async removePathItemRelationalByItemId(itemId: string) {
    const result = await this.pathItemRelationalRepository.delete({ item_id: itemId });
    if (result.affected && result.affected > 0) {
      return `成功删除 ${result.affected} 条记录`;
    } else {
      return `未找到匹配的记录，没有进行删除操作`;
    }
  }

  async remove(id: string) {
    const result = await this.pathItemRelationalRepository.delete({ id: id });
    if (result.affected && result.affected > 0) {
      return `成功删除 ${result.affected} 条记录`;
    } else {
      return `未找到匹配的记录，没有进行删除操作`;
    }
  }
}
